﻿package znet

import (
	"fmt"
	"zxGoServer/zinterface"
)

type MsgHandle struct {

	//Apis map[uint32]
	WorkerPoolSize uint32                     //业务工作Worker池的数量
	TaskQueue      []chan zinterface.IRequest //Worker负责取任务的消息队列
}

func NewMsgHandle(workerPoolSize uint32) *MsgHandle {

	return &MsgHandle{
		WorkerPoolSize: workerPoolSize,
		TaskQueue:      make([]chan zinterface.IRequest, workerPoolSize),
	}
}

func (mh *MsgHandle) DoMsgHandler(request zinterface.IRequest) {

}

func (mh *MsgHandle) SendMsgToTaskQueue(request zinterface.IRequest) {

	workerId := request.GetConnection().GetConnID() % mh.WorkerPoolSize
	mh.TaskQueue[workerId] <- request
}

// 启动一个Worker工作流程
func (mh *MsgHandle) StartOneWorker(workerID int, taskQueue chan zinterface.IRequest) {
	fmt.Println("Worker ID = ", workerID, " is started.")
	//不断的等待队列中的消息
	for {
		select {
		//有消息则取出队列的Request，并执行绑定的业务方法
		case request := <-taskQueue:
			mh.DoMsgHandler(request)
		}
	}
}

func (mh *MsgHandle) StartWorkerPool() {
	for i := 0; i < int(mh.WorkerPoolSize); i++ {
		mh.TaskQueue[i] = make(chan zinterface.IRequest, mh.WorkerPoolSize)
		go mh.StartOneWorker(i, mh.TaskQueue[i])
	}
}
